package com.smile.cloud.points.consume;


import com.alibaba.fastjson.JSONObject;
import com.smile.cloud.points.consume.core.DedupConcurrentListener;
import com.smile.cloud.points.consume.core.DedupConfig;
import com.smile.cloud.points.service.OrderDTO;
import com.smile.cloud.points.service.PointsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;

import java.nio.charset.StandardCharsets;

/**
 * @author LGC
 */
@Slf4j
public class OrderListener extends DedupConcurrentListener {

    @Autowired
    private PointsService pointsService;

    public OrderListener(DedupConfig dedupConfig) {
        super(dedupConfig);
    }

    /**
     * 基于什么做消息去重，每一类不同的消息都可以不一样，做去重之前会尊重此方法返回的值
     *
     * @param messageExt
     * @return
     */
    @Override
    protected String dedupMessageKey(MessageExt messageExt) {
        //用订单编号作为去重键
        if (OrderConsumer.TOPIC.equals(messageExt.getTopic())) {
            OrderDTO order = JSONObject.parseObject(messageExt.getBody(), OrderDTO.class);
            return order.getOrderNo();
        } else {//其他使用默认的配置（消息id）
            return super.dedupMessageKey(messageExt);
        }

    }

    @Override
    protected boolean doHandleMsg(MessageExt messageExt) {
        String topic = messageExt.getTopic();
        String tags = messageExt.getTags();
        String body = new String(messageExt.getBody(), StandardCharsets.UTF_8);
        log.info("receive MQ消息 topic={}, tags={}, msg={},messageExt={}", topic, tags, body, messageExt);
        if (OrderConsumer.TOPIC.equals(messageExt.getTopic())) {
            log.info("监听到订单数据消息...");
            try {
                log.info("开始处理订单数据，准备增加积分...");
                OrderDTO order = JSONObject.parseObject(messageExt.getBody(), OrderDTO.class);
                pointsService.increasePoints(order);
            } catch (Exception e) {
                log.error("处理订单数据发生异常。{0}", e);
            }
        }
        return true;
    }

}
